<?php

namespace App\Service\ChatGroup\AiBot\WhoBot;

use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Remote\WhoBot\ChatRemote;
use App\Service\BaseService;
use App\Service\ChatGroup\AiBot\AbstractBotService;
use App\Service\ChatGroup\ChatGroupAiChatService;
use App\Service\ChatGroup\ChatGroupStructService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Request;
use Illuminate\Validation\ValidationException;

class WhoBotService extends AbstractBotService
{
    protected array $lastMsg = [];

    /**
     * WhoBot 的机器人聊天
     *
     * @param array $message
     * @return mixed
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function chat(array $message)
    {
        // 写死商家端
        $requestSource = '商家端';
        return ChatRemote::sendChat(
            $this->lastMsg['senderUid'],
            $this->lastMsg['id'],
            $this->lastMsg['sessionId'],
            $requestSource,
            $message);
    }


    public function handelData(array $orgMsg): array
    {
        if (!count($orgMsg)) {
            return [];
        }

        $this->lastMsg = end($orgMsg);

        $messages = $orgMsg;
        $count    = count($messages);
        for ($i = 0; $i < $count - 1; $i++) {
            // 检查是否存在下一个元素以及当前元素是否可以与下一个元素合并
            if (isset($messages[$i + 1]) &&
                $messages[$i]['senderUid'] === $messages[$i + 1]['senderUid'] &&
                abs($messages[$i]['createdAtTimestamp'] - $messages[$i + 1]['createdAtTimestamp']) <= ChatGroupAiChatService::MESSAGE_MERGE_TIME) {

                // 合并内容到当前元素
                $messages[$i]['content']            .= PHP_EOL . $messages[$i + 1]['content'];
                $messages[$i]['createdAtTimestamp'] = $messages[$i + 1]['createdAtTimestamp'];
                // 如果下一个元素的时间戳更大，则更新当前元素的时间戳
                if ($messages[$i + 1]['createdAtTimestamp'] > $messages[$i]['createdAtTimestamp']) {
                    $messages[$i]['createdAtTimestamp'] = $messages[$i + 1]['createdAtTimestamp'];
                }
                // 删除下一个元素
                array_splice($messages, $i + 1, 1);
                // 减少数组长度计数
                $count--;
                // 因为当前元素已经与下一个元素合并，所以要重新检查当前元素是否还能与新的下一个元素合并
                $i--;
            }
        }

        $orgMsg = $messages;
        $result = [];
        foreach ($orgMsg as $item) {
            $roleText = '';
            if ($item['senderUid'] == ChatGroupUserModel::KUA_XIAO_FU_USER_ID) {
                $roleText = 'AI客服';
            } else {
                $roleText = $item['roleText'];
            }
            $result[] = [
                "role"    => $roleText,
                "content" => $item['content'],
            ];
        }

        return $result;
    }
}
